/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author gravena
 */
public class File {

    public static final String sharePath = "./";
    private String name;
    private HashMD5 hashMD5;
    private long size;
    private boolean complete;

    public File(String name) throws IOException {
        java.io.File file = new java.io.File(File.sharePath + name);

        if (!file.exists()) {
            throw new IOException("Arquivo não encontrado!");
        }

        this.size = file.length();
        this.name = name;
        this.hashMD5 = new HashMD5(this.calculateCheckSum());
        this.complete = true;
    }

    public File() {
    }

    /**
     * Retorna o tamanho que o registro deste arquivo precisará em um pacote de listagem
     * @return Tamanho em bytes
     */
    public int getRecordSize() {
        int nSize = this.name.length();

        return 16 + 8 + 4 + nSize + 1; /* MD5 Hash + long + int + name length */
    }

    public final byte[] calculateCheckSum() {
        InputStream fis;
        try {
            fis = new FileInputStream(this.name);

            byte[] buffer = new byte[1024];
            MessageDigest complete;
            complete = MessageDigest.getInstance("MD5");

            int numRead;

            do {
                numRead = fis.read(buffer);
                if (numRead > 0) {
                    complete.update(buffer, 0, numRead);
                }
            } while (numRead != -1);

            fis.close();
            return complete.digest();
        } catch (NoSuchAlgorithmException | IOException ex) {
            System.err.println("Erro ao calcular o Hash!\n" + ex.getMessage());
            return null;
        }
    }

    public String getName() {
        return name;
    }

    public long getSize() {
        return size;
    }

    @Override
    public String toString() {
        return "Nome: " + this.name + "\nTamanho: " + this.size + "\nHash MD5: " + this.hashMD5.getData().length;
    }

    public byte[] getHashMD5() {
        return hashMD5.getData();
    }

    public HashMD5 getHashMD5Wrapper() {
        return hashMD5;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setHashMD5(byte[] hashMD5) {
        this.hashMD5 = new HashMD5(hashMD5);
    }

    public void setSize(long size) {
        this.size = size;
    }

    public boolean isComplete() {
        return complete;
    }

    public void setComplete(boolean complete) {
        this.complete = complete;
    }
    
    
}
